// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package traffic

import (
	"os"
	"path/filepath"
	"time"

	"git.sr.ht/~sircmpwn/go-bare"
)

type TrafficResult interface {
	getTraffic() *Traffic
	getContext() Context
	setTimezone(*time.Location)
	setStopsFile(*os.File)
	getTimetableHome() string
	getStopsFile() *os.File
	getStopOffset() uint
	setStop(Stop)
	setTripsFile(*os.File)
	getTripsFile() *os.File
}

func loadTimezone(r TrafficResult) (TrafficResult, error) {
	l, err := GetTimezone(Stop{}, r.getTraffic(), r.getContext().FeedID)
	r.setTimezone(l)
	return r, err
}

func openStopsFile(r TrafficResult) (TrafficResult, error) {
	file, err := os.Open(filepath.Join(r.getTimetableHome(), "stops.bare"))
	r.setStopsFile(file)
	return r, err
}

func seekStopsFile(r TrafficResult) (TrafficResult, error) {
	_, err := r.getStopsFile().Seek(int64(r.getStopOffset()), 0)
	return r, err
}

func unmarshallStop(r TrafficResult) (TrafficResult, error) {
	stop := Stop{}
	err := bare.UnmarshalReader(r.getStopsFile(), &stop)
	r.getStopsFile().Close()
	r.setStop(stop)
	return r, err
}

func openTripsFile(r TrafficResult) (TrafficResult, error) {
	file, err := os.Open(filepath.Join(r.getTimetableHome(), "trips.bare"))
	r.setTripsFile(file)
	return r, err
}

func closeFiles(r TrafficResult, err error) (TrafficResult, error) {
	if r.getStopsFile() != nil {
		r.getStopsFile().Close()
	}
	if r.getTripsFile() != nil {
		r.getTripsFile().Close()
	}
	return r, err
}
